const jwt = require('jsonwebtoken');
const { JWT_SECRET } = require('../config/config');
const { unauthorized } = require('../utils/response');

const authMiddleware = (req, res, next) => {
  // 从请求头获取token
  const token = req.header('Authorization')?.replace('Bearer ', '');
  
  if (!token) {
    return unauthorized(res, '未提供认证令牌');
  }
  
  try {
    // 验证token
    const decoded = jwt.verify(token, JWT_SECRET);
    req.user = decoded;
    next();
  } catch (err) {
    return unauthorized(res, '无效的认证令牌');
  }
};

module.exports = authMiddleware;